package com.ezcoding.service;

import com.ezcoding.dao.CompanyDao;
import com.ezcoding.dao.UserDao;
import com.ezcoding.model.Company;
import com.ezcoding.model.User;
import com.ezcoding.trade.TradeInterface;
import com.ezcoding.utils.DateUtil;
import com.ezcoding.utils.StatusUtil;
import com.ezcoding.utils.Tools;

import java.util.HashMap;
import java.util.Map;

public class TradeService {
    private static TradeService instance = new TradeService();

    public static TradeService getInstance() {
        return instance;
    }

    public Map<String, Object> getQrCode(String username, int day, String totalAmount) {
        if (Tools.checkParaIsInValidate(username, totalAmount)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        if (UserDao.dao.getUserByUsername(username) == null) {
            return StatusUtil.getFailedStatusWithMessage("用户不存在！");
        }

        String subject = String.format("用户%s续费[%d天]", username, day);
        String body = String.format("%s#%d#%s", username, day, totalAmount);

        TradeInterface tradeInterface = new TradeInterface();

        String qrCode = tradeInterface.test_trade_precreate(subject, totalAmount, body);

        if (!qrCode.contains("https")) {
            return StatusUtil.getFailedStatusWithMessage(qrCode);
        }

        Map<String, Object> res = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        data.put("qrCode", qrCode);
        res.put("data", data);

        return StatusUtil.getSuccessStatusWithMessage(res, "获取成功！");
    }

    public Map<String, Object> queryUserInfo(String username) {
        if (Tools.checkParaIsInValidate(username)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        User user = UserDao.dao.getUserByUsername(username);

        if (user == null) {
            return StatusUtil.getFailedStatusWithMessage("查询账号不存在！");
        }

        Company company = CompanyDao.dao.getCompanyByCompanyId(user.getCompanyId());

        Map<String, Object> res = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        data.put("query_user", user);
        if (company != null) {
            data.put("companyName", company.getCompanyName());
        }
        data.put("server_date", DateUtil.getCurrentDate());
        data.put("is_valid", DateUtil.isValid(user.getEndDate())?1:0);
        res.put("data", data);

        System.out.println(data);

        return StatusUtil.getSuccessStatusWithMessage(res, "查询成功！");
    }
}
